/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tencent.tendon.convert.json;

/**
 *
 * @author nbzhang
 */
@SuppressWarnings("unchecked")
public final class JsonObjectEncoder<T> extends JsonEncoder<T> {

	private JsonEnHandle head;

	private JsonInterceptor<T> interceptor;

	JsonObjectEncoder(Class<T> type) {
		super(type);
		this.head = JsonEnHandle.NULL;
	}

	void setJsonEnHandle(JsonEnHandle head) {
		this.head = head;
	}

	void setJsonInterceptor(JsonInterceptor<T> interceptor) {
		this.interceptor = interceptor;
	}

	@Override
	public String toString() {
		return this.getClass().getSimpleName() + "{type:" + this.type + ", simpled:" + simpled + ",\r\n   next:" + this.head + "}";
	}

	@Override
	public void convertTo(final JsonWriter out, final T value0) {
		final T value = (interceptor == null) ? value0 : interceptor.preEncode(value0);
		if (this.simpled) {
			out.write('{');
			boolean comma = false;
			JsonEnHandle handle = this.head;
			do {
				comma = handle.writeValue(out, comma, value);
			} while ((handle = handle.next) != null);
			out.write('}');
		} else {
			if (out.writeRefer(value)) return;
			out.offer(value);
			out.write('{');
			boolean comma = false;
			JsonEnHandle handle = this.head;
			do {
				comma = handle.writeValue(out, comma, value);
			} while ((handle = handle.next) != null);
			out.write('}');
			out.poll();
		}
	}
}
